#!/usr/bin/env script/runner

# Ferret DRb server launcher script
#
# Place doc/ferret_server.yml into RAILS_ROOT/config and fit to taste. Start
# it with RAILS_ENV set to the desired environment.
#
#
# To run the demo project's unit tests against the drb server, start it with
# 
# RAILS_ENV=test script/ferret_start 
#
# and run your tests with the AAF_REMOTE environment variable set to a 
# non-empty value:
#
# AAF_REMOTE=true rake
#
# The server writes a log file in log/ferret_server.log, it's 
# STDOUT gets redirected to log/ferret_server.out


config = ActsAsFerret::Remote::Config.load
@pid_file = config['pid_file']

def write_pid_file
    open(@pid_file,"w") {|f| f.write(Process.pid) }
end

def safefork
  tryagain = true

  while tryagain
    tryagain = false
    begin
      if pid = fork
        return pid
      end
    rescue Errno::EWOULDBLOCK
      sleep 5
      tryagain = true
    end
  end
end

safefork and exit
at_exit do
  File.unlink(@pid_file) if @pid_file && File.exists?(@pid_file) && File.read(@pid_file).to_i == Process.pid
end
print "Starting ferret DRb server..."
trap("TERM") { exit(0) }
sess_id = Process.setsid


begin
  ActsAsFerret::Remote::Server.start
  write_pid_file
  puts "Done."
  STDIN.reopen "/dev/null"                                 # Free file descriptors and
  STDOUT.reopen "#{RAILS_ROOT}/log/ferret_server.out", "a" # point them somewhere sensible
  STDERR.reopen STDOUT                                     # STDOUT/STDERR should go to a logfile
rescue
  puts "Error starting ferret DRb server: #{$!}"
  exit(1)
end
DRb.thread.join

# vim:set filetype=ruby:
